var User = {
	init: function() {
		User.typeInit();
		$("#save").click(function() {
			var reg = /^([A-Za-z0-9]{6,16})$/;
			var data = new Object();
			data.category = $("#userType").val();
			data.email = $("#email").val();
			data.phone = $("#phone").val();
			data.username = $("#username").val();
			data.password = $("#password").val();
			data.newpassword = $("#newpassword").val();
			$("#form").find("input").each(function() {
				data[$(this).attr("id")] = $(this).val();
			});
			//TODO 检查email/phone的合法性

			if (checkEmail(data.email) == false)
				return;
			if (checkMobile(data.phone) == false)
				return;
			if (!reg.test(data.username))
				return $alert("用户名不正确");
			if (data.password == "")
				return $alert("密码不能为空");
			if (data.password !== data.newpassword)
				return $alert("密码与确认密码不同，请重新输入！");
			$ajax({
				url: "/user/reg",
				data: data,
				success: function(res) {
					if (res.code == 0) {
						$alert("创建成功");
						window.location.href = "userList.html";
					}
				}
			});
		});
	},
	typeInit: function(flag) {
		var html = "";
		var typeList = UTYPETEXT[CurrentUser.category];
		var length = typeList && typeList.length || 0;
		for (var i = 0; i < length; i++) {
			html += "<option value='" + typeList[i].type + "'>" + typeList[i].text + "</option>";
		}
		if (flag)
			html += "<option value='" + UTYPE.STUDENT + "'>学员</option>";
		$("#userType").html(html);
	},
	listInit: function() {
		User.typeInit("list");
		User.userJump($("#userType").val(), 1);
		SetLS("usertype", $("#userType").val());
		$("#userType").change(function() {
			SetLS("usertype", $("#userType").val());
			User.userJump($("#userType").val(), 1);
		});
	},
	userClick: function(pageclickednumber) {
		var cont = GetLS("cont");
		User.userJump(GetLS("usertype"), pageclickednumber);
		$("#listPager").pager({
			pagenumber: pageclickednumber,
			pagecount: cont,
			buttonClickCallback: User.userClick
		});
	},
	userJump: function(type, pageno) {
		var count = Res.sinCount;
		var start = (pageno - 1) * count;
		$ajax({
			url: "/user/list",
			data: {
				start: start,
				count: count,
				category: type
			},
			success: function(res) {
				var list = res.result;
				var list = res.result.results;
				var cont = parseInt(res.result.count / Res.sinCount);
				if ((res.result.count) % Res.sinCount != 0) {
					cont++;
				}
				SetLS("cont", cont);
				$("#listPager").pager({
					pagenumber: pageno,
					pagecount: cont,
					buttonClickCallback: User.userClick
				});
				var html = '<thead>' +
					'    <tr>' +
					'        <th class="span2">用户名</th>' +
					'        <th class="span3">昵称</th>' +
					'        <th class="span3">邮箱</th>' +
					'        <th class="span2">手机号</th>' +
					'        <th class="span2">操作</th>' +
					'    </tr>' +
					'</thead>' +
					'<tbody>';;
				for (var i = 0; i < list.length; i++) {
					html += "<tr>" +
						"    <td>" + list[i].username + "</td>" +
						"    <td>" + (list[i].name ? list[i].name : "无") + "</td>" +
						"    <td>" + list[i].email + "</td>" +
						"    <td>" +
						"        <span>" + list[i].phone + "</span>" +
						"    </td>" +
						"    <td>" +
						// "        <div class='text-right'>" + 
						"				<button data-id='" + list[i]._id + "' class='btn btn-success updateBtn'>修改</button>" +
						"				<button data-id='" + list[i]._id + "' class='btn btn-danger btn-sm removeBtn'>删除</button>" +
						// "        </div>" + 
						"    </td>" +
						"</tr>";
				}
				html += "</tbody>";
				$("#userList").html(html);
				$(".updateBtn").click(function() {
					window.location.href = "userUpdate.html?id=" + $(this).data("id");
				});
				$(".removeBtn").click(function() {
					if (!confirm("确定要删除吗?"))
						return;
					var $this = $(this).parent().parent();
					$ajax({
						url: "/user/remove",
						data: {
							_id: $(this).data("id")
						},
						success: function(res) {
							$this.remove();
						}
					});
				});
			}
		});
	},
	updateInit: function() {
		User.typeInit("list");
		$ajax({
			url: "/user/detail",
			data: {
				_id: getValue("id")
			},
			success: function(res) {
				var user = res.result;
				$("#userType").val(user.category);
				$("#form").find("input").each(function() {
					$(this).val(user[$(this).attr("id")]);
				});
				$("#update").click(function() {
					var reg = /^([A-Za-z0-9]{6,16})$/;
					var data = user;
					data.category = $("#userType").val();
					$("#form").find("input").each(function() {
						data[$(this).attr("id")] = $(this).val();
					});
					if (checkEmail(data.email) == false)
						return;
					if (checkMobile(data.phone) == false)
						return;
					if (!reg.test(data.username))
						return $alert("用户名不正确");
					$ajax({
						url: "/user/upsert",
						data: data,
						success: function(res) {
							$alert("修改成功");
							window.location.href = "userList.html";
						}
					});
				});
			}
		});
	},

	profileInit: function() {
		$("#des").val(CurrentUser.des);
		$("#education").val(CurrentUser.education);
		$("#email").val(CurrentUser.email);
		$("#name").val(CurrentUser.name);
		$("#username").val(CurrentUser.username);
		$("#phone").val(CurrentUser.phone);
		$("#save").click(User.profileSave);
	},

	profileSave: function() {
		CurrentUser.des = $("#des").val();
		CurrentUser.education = $("#education").val();
		CurrentUser.email = $("#email").val();
		CurrentUser.name = $("#name").val();
		CurrentUser.username = $("#username").val();
		CurrentUser.phone = $("#phone").val();
		if (checkEmail(CurrentUser.email) == false)
			return;
		if (checkUserName(CurrentUser.username) == false)
			return;
		if (checkMobile(CurrentUser.phone) == false)
			return;
		$ajax({
			url: "/user/upsert",
			data: CurrentUser,
			success: function(res) {
				$alert("修改成功");
				SetLS("user",CurrentUser);
			}
		});
	},

	updatePwd: function() {
		$("#updatePwd").click(function() {
			var pwd = $("#password").val();
			var newpwd = $("#newpass").val();
			var rnewpwd = $("#rnewpass").val();

			if (pwd == "" || newpwd == "" || rnewpwd == "")
				return $alert("原密码，新密码，确认密码均不能为空");
			if (newpwd != rnewpwd)
				return $alert("新密码和确认密码不同");

			//TODO:CurrentUser.password已经md5，需要把pwd做md5后和它进行比较
			//if(pwd != CurrentUser.password)
			//	return $alert("原密码不正确");

			CurrentUser.password = newpwd;
			CurrentUser.oldPassword = pwd;
			$ajax({
				url: "/user/updatePassword",
				data: CurrentUser,
				success: function(res) {
					$alert("修改成功");
				}
			});
		});
	},
	findPass: function() {
		var str = $("#email").val(); //获取框里输入的值
		var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/; //core里的验证邮箱
		var pre = /^1\d{10}$/; //core里的验证手机号码
		var field = re.test(str) ? "email" : "" || pre.test(str) ? "phone" : "";
		if (field) { //re 对就对 pre对也对
			// to do...
			// alert("格式正确");//对啦 就正确
			$ajax({
				url: "/user/findPwd",
				data: {
					value: str, //传str那个东东
					field: field,

				},
				success: function(res) {
					$alert("发送成功");
				}
			});

		} else
			return $alert("请输入正确的邮箱或手机号码"); //错啦或者空就显示格式错误
	},
	findPassword: function() {
		$("#findPassword").click(function() {
			var value = $.trim($("#email").val());
			var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/; 
			var pre = /^1\d{10}$/; 
			var field = re.test(value) ? "email" : "" || pre.test(value) ? "phone" : "";
			var saveq = $("#saveq").val();
			var newpwd = $("#newpass").val();
			var rnewpwd = $("#rnewpass").val();
			if (newpwd == "" || rnewpwd == "" || saveq == "")
				return $alert("验证码，新密码，确认密码均不能为空");
			if (newpwd != rnewpwd)
				return $alert("新密码和确认密码不同");
			var user = {
				password : newpwd,
				code : saveq,
				value : value,
				field : field
			};
			$ajax({
				url: "/user/resetPassword",
				data: user,
				success: function(res) {
					$alert("提交成功");
					window.location.href = "signup.html";
				}
			});
		});
	}
}